package edu.ccut.saturn.web.listener;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.PiePlot;

import edu.ccut.saturn.component.ComponentManager;
import edu.ccut.saturn.component.ILogger;
import edu.ccut.saturn.component.SaturnAuthorityManager;
import edu.ccut.saturn.component.SaturnDictionaryManager;
import edu.ccut.saturn.component.SaturnLoggerManager;
import edu.ccut.saturn.component.SaturnMenuManager;
import edu.ccut.saturn.component.SaturnTaskManager;
import edu.ccut.saturn.component.SaturnWorkFlowManager;
import edu.ccut.saturn.component.loader.DictionaryLoader;
import edu.ccut.saturn.component.utils.ExceptionUtils;
import edu.ccut.saturn.component.utils.SaturnMemCacheManager;
import edu.ccut.saturn.core.IConstants;
import edu.ccut.saturn.core.IPropertiesService;
import edu.ccut.saturn.core.impl.SaturnPropertiesService;
import edu.ccut.saturn.osgi.OSGiBundleLoader;

public class BundlesContextListener implements ServletContextListener {

	protected static ILogger logger = SaturnLoggerManager.getInstance()
			.getSaturnLogger(SaturnLoggerManager.LOGGER_KEY_COMPONENT_RUNTIME);

	private OSGiBundleLoader osgiWebappLoader;

	public void contextInitialized(ServletContextEvent event) {
		ServletContext context = event.getServletContext();

		try {
			initProperties(context);
			initCache();
			initJfreechart();
			
			startOSGi();
			
			loadDictionary();
			initServletContext(context);

			SaturnTaskManager.getInstance().loadStartComponent();
		} catch (Exception e) {
			logger.error(ExceptionUtils.getExMessage(e));
		}

	}

	/**
	 * 启动OSGi容器
	 * @throws Exception
	 */
	private void startOSGi() throws Exception {
		osgiWebappLoader = new OSGiBundleLoader(SaturnPropertiesService
				.getInstance().getProperty(
						IConstants.SATURN_CONFIG_LOCATION),
				SaturnPropertiesService.getInstance().getProperty(
						IConstants.SATURN_BUNDLES_HOME));

		osgiWebappLoader.startup();
	}

	/**
	 * 根据配置启动缓存服务
	 */
	private void initCache() {
		if ("true".equals(SaturnPropertiesService.getInstance().getProperty(
				IConstants.SATURN_COMPONENTINFO_CACHE_INSTRUCTION))) {
			SaturnMemCacheManager.getInstance().start();
		}
	}

	public void contextDestroyed(ServletContextEvent event) {
		this.osgiWebappLoader.shutdown();
	}

	/**
	 * 这个方法仅仅创建一个JFreeChart对象,目的是为了在启动OSGi之前对JFreeChart内部完成初始化操作,
	 * 否则在Eclipse中启动web服务器会导致JFreeChart初始化失败.
	 */
	private void initJfreechart() {
		try {
			new JFreeChart("title", JFreeChart.DEFAULT_TITLE_FONT,
					new PiePlot(), true);
		} catch (Exception e) {
		}
	}

	/**
	 * 加载Saturn配置到ISaturnPropertiesService
	 * 
	 * @param context
	 * @see IPropertiesService
	 */
	private void initProperties(ServletContext context) {
		IPropertiesService saturnPropertiesService = SaturnPropertiesService
				.getInstance();

		saturnPropertiesService.addProperties(System.getProperties());

		saturnPropertiesService.setProperty(
				IConstants.SATURN_SERVER_LOCATION, context
						.getRealPath(""));

		String cacheLocation = context
				.getInitParameter("webContainerCacheDirectory");

		if (cacheLocation == null) {
			cacheLocation = "work";
		}
		saturnPropertiesService.setProperty(
				IConstants.SATURN_WEB_CONTAINER_JSP_CACHE_LOCATION,
				cacheLocation);

		String isLazyLoad = context.getInitParameter("isLazyLoad");

		if (isLazyLoad == null) {
			isLazyLoad = "false";
		}
		saturnPropertiesService.setProperty(
				IConstants.SATURN_COMPONENTINFO_LOADER_INSTRUCTION,
				isLazyLoad);

		String isCacheLoad = context.getInitParameter("isCacheLoad");

		if (isCacheLoad == null) {
			isCacheLoad = "false";
		}
		saturnPropertiesService.setProperty(
				IConstants.SATURN_COMPONENTINFO_CACHE_INSTRUCTION,
				isCacheLoad);

		String bundlesHomeLocation = context
				.getInitParameter("osgiBundlesHomeLocatoin");

		if (bundlesHomeLocation == null) {
			bundlesHomeLocation = "WEB-INF/bundles";
		}
		saturnPropertiesService.setProperty(
				IConstants.SATURN_BUNDLES_HOME, context
						.getRealPath(bundlesHomeLocation));

		String configPropertiesLocation = context
				.getInitParameter("osgiConfigLocation");

		if (configPropertiesLocation == null) {
			configPropertiesLocation = "WEB-INF/config.properties";
		}
		saturnPropertiesService.setProperty(
				IConstants.SATURN_CONFIG_LOCATION, context
						.getRealPath(configPropertiesLocation));

	}
    /**
     * 
     * @param context
     */
	private void initServletContext(ServletContext context) {
		context.setAttribute("osgi", osgiWebappLoader);
		context.setAttribute("component", ComponentManager.getInstance());
		context.setAttribute("dict", SaturnDictionaryManager.getInstance());
		context.setAttribute("workflow", SaturnWorkFlowManager.getInstance());
		context.setAttribute("authority", SaturnAuthorityManager.getInstance());
		context.setAttribute("menu", SaturnMenuManager.getInstance());
		context.setAttribute("task", SaturnTaskManager.getInstance());
	}

	private void loadDictionary() {
		DictionaryLoader.loadDataDictTypeInfo();
	}
}
